using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 个人的天光；初始化时layer置空，只作为 MainLit;一个 handler 可控制多个 CharacterLit;
/// </summary>
#if UNITY_2017_1_OR_NEWER
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[RequireComponent(typeof(MeshRenderer))]
public class CharacterLit : MonoBehaviour
{
    [Header("需要人物光的部件")]
    [Header("会加1个透明的面片，避免单看部位时没WillRender")]//基于OnWillRenderObject（），所以如何是一个点判断，则某些镜头角度不渲染人物光，所以需要一个透明面片，覆盖所有需要人物光的部件
    
    public List<Renderer> _renderer;
    [Header("自动获取当前Go 的 Light")]
    public Light _light;

    private static readonly int SelfIntensity = Shader.PropertyToID("_SelfIntensity");

    private void OnEnable()
    {
        _light = GetComponent<Light>();
        ShowLit();
    }

    private void OnDisable()
    {
        DisappearLit();
    }

    void ShowLit()
    {
        if (_renderer == null) return;
        if (_renderer.Count == 0) return;
        if (_light == null) return;
        _light.enabled = true;
    }

    void DisappearLit()
    {
        if (_renderer == null) return;
        if (_renderer.Count == 0) return;
        if (_light == null) return;
        _light.enabled = false;
        ResetRendererLit(_renderer);
    }

    void ResetRendererLit(List<Renderer> renders)
    {
        foreach (var renderer in renders)
        {
            ResetRendererLit(renderer);
        }
    }

    void ResetRendererLit(Renderer renderer)
    {
        Material mat = renderer.sharedMaterial;
        if (mat != null)
        {
            mat.SetColor("_SelfMainLight", Color.black);
        }
    }

    void OnWillRenderObject()
    {
        if (_renderer == null) return;
        if (_light == null) return;
        if (_light.enabled == false)
        {
            //设置原始颜色
            ResetRendererLit(_renderer);
            return;
        }

        foreach (var renderer in _renderer)
        {
            Material mat = renderer.sharedMaterial;
            if (mat != null)
            {
                mat.SetColor("_SelfMainLight", _light.color);
            
                var dir = _light.transform.rotation.eulerAngles;
                //Debug.LogError("rot=" + dir);
                mat.SetVector("_SelfDir", new Vector4(dir.x, dir.y, dir.z, 1));
                mat.SetFloat(SelfIntensity,_light.intensity);
                
                
                //测试方位用，现在没用
                // var pos = _light.transform.position;
                // mat.SetVector("_SelfDir", new Vector4(pos.x, pos.y, pos.z, 0));
            }
        }
       
    }
    


}
